﻿/************************************************************************************
 * Copyright (c) 2016 北京大象科技有限公司 All Rights Reserved.
 * CLR版本：4.0.30319.42000
 *公司名称：北京大象科技有限公司
 *命名空间：ET.Database
 *文件名：  DbHelper
 *版本号：  V1.0.0.0
 *唯一标识：a5bc99c5-4ddd-4042-adb6-dc71b1ce7678
 *创建人：  杜鹏
 *电子邮箱：dupeng@bjdaxiang.cn
 *QQ:       4909004
 *创建时间：2016/3/19 15:25:44
 *描述：    
 *
 *=====================================================================
 *修改标记 
 *修改时间：2016/3/19 15:25:44
 *修改人：  杜鹏
 *版本号：  V1.0.0.0
 *描述：
/************************************************************************************/

using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace ET.DBCommon
{
    /// <summary>
    /// 数据库操作类
    /// </summary>
    public class DbHelper
    {
        public static string connStr = ConfigurationManager.AppSettings["CompetitionDbConnStr"];
        /// <summary>
        /// 获取最后添加Id
        /// </summary>
        /// <returns></returns>
        public static string GetLastIdSql()
        {
            return "SELECT LAST_INSERT_ID()";
        }


        #region ExecuteNonQuery方法

        /// <summary>
        /// 执行指定连接字符串,类型的SqlCommand.
        /// </summary>
        /// <remarks>
        /// 示例:  
        ///  int result = ExecuteNonQuery("SELECT * FROM [table123]");
        /// </remarks>
        /// <param name="connStr">数据库连接字符串</param>
        /// <param name="commandText">存储过程名称或SQL语句</param>
        /// <returns>返回命令影响的行数</returns>
        public static int ExecuteNonQuery(string commandText)
        {
            return ExecuteNonQuery(CommandType.Text, commandText, (MySqlParameter[])null);
        }

        /// <summary>
        /// 执行指定连接字符串,类型的SqlCommand.
        /// </summary>
        /// <remarks>
        /// 示例:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders");
        /// </remarks>
        /// <param name="connStr">数据库连接字符串</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本, 其它.)</param>
        /// <param name="commandText">存储过程名称或SQL语句</param>
        /// <returns>返回命令影响的行数</returns>
        public static int ExecuteNonQuery(CommandType commandType, string commandText)
        {
            return ExecuteNonQuery(commandType, commandText, (MySqlParameter[])null);
        }


        public static int ExecuteNonQuery(string commandText, params MySqlParameter[] commandParameters)
        {
            return ExecuteNonQuery(CommandType.Text, commandText, commandParameters);
        }

        /// <summary>
        /// 执行指定连接字符串,类型的SqlCommand.如果没有提供参数,不返回结果.
        /// </summary>
        /// <remarks>
        /// 示例:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connStr">数据库连接字符串</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本, 其它.)</param>
        /// <param name="commandText">存储过程名称或SQL语句</param>
        /// <param name="commandParameters">SqlParameter参数数组</param>
        /// <returns>返回命令影响的行数</returns>
        public static int ExecuteNonQuery(CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            if (connStr == null || connStr.Length == 0) throw new ArgumentNullException("ConnectionString");

            using (MySqlConnection connection = new MySqlConnection())
            {
                connection.ConnectionString = connStr;
                connection.Open();

                if (connection == null) throw new ArgumentNullException("connection");

                // 创建SqlCommand命令,并进行预处理
                MySqlCommand cmd = new MySqlCommand();
                bool mustCloseConnection = false;
                PrepareCommand(cmd, connection, (MySqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);

                int retval = 0;
                try
                {
                    // 执行SqlCommand命令,并返回结果.
                    retval = cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    retval = -1;
                    ;// throw ex;
                }

                // 清除参数,以便再次使用.
                cmd.Parameters.Clear();
                if (mustCloseConnection)
                    connection.Close();
                return retval;
            }
        }



        /// <summary>
        /// 执行指定连接字符串,类型的SqlCommand.
        /// </summary>
        /// <remarks>
        /// 示例:  
        ///  int result = ExecuteNonQuery("SELECT * FROM [table123]");
        /// </remarks>
        /// <param name="id"></param>
        /// <param name="connStr">数据库连接语句</param>
        /// <param name="commandText">存储过程名称或SQL语句</param>
        /// <returns>返回命令影响的行数</returns>
        public static int ExecuteNonQuery(out int id, string commandText)
        {
            return ExecuteNonQuery(out id, CommandType.Text, commandText, (MySqlParameter[])null);
        }

        public static int ExecuteNonQuery(out int id, string commandText, params MySqlParameter[] commandParameters)
        {
            return ExecuteNonQuery(out id, CommandType.Text, commandText, commandParameters);
        }

        /// <summary>
        /// 执行指定连接字符串,并返回刚插入的自增ID
        /// </summary>
        /// <remarks>
        /// 示例:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders");
        /// </remarks>
        /// <param name="id"></param>
        /// <param name="connStr">数据库连接语句</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本, 其它.)</param>
        /// <param name="commandText">存储过程名称或SQL语句</param>
        /// <returns>返回命令影响的行数</returns>
        public static int ExecuteNonQuery(out int id, CommandType commandType, string commandText)
        {
            return ExecuteNonQuery(out id, commandType, commandText, (MySqlParameter[])null);
        }


        /// <summary>
        /// 执行指定连接字符串并返回刚插入的自增ID,类型的SqlCommand.如果没有提供参数,不返回结果.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="connStr">数据库连接语句</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本, 其它.)</param>
        /// <param name="commandText">存储过程名称或SQL语句</param>
        /// <param name="commandParameters">SqlParameter参数数组</param>
        /// <returns>返回命令影响的行数</returns>
        public static int ExecuteNonQuery(out int id, CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            try
            {
                if (connStr == null || connStr.Length == 0) throw new ArgumentNullException("ConnectionString");

                using (MySqlConnection connection = new MySqlConnection())
                {
                    connection.ConnectionString = connStr;

                    if (connection == null) throw new ArgumentNullException("connection");
                    if (GetLastIdSql().Trim() == "") throw new ArgumentNullException("GetLastIdSql is \"\"");

                    // 创建SqlCommand命令,并进行预处理
                    MySqlCommand cmd = new MySqlCommand();
                    bool mustCloseConnection = false;
                    PrepareCommand(cmd, connection, (MySqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);

                    // 执行命令
                    int retval = cmd.ExecuteNonQuery();
                    // 清除参数,以便再次使用.
                    cmd.Parameters.Clear();
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = GetLastIdSql();

                    //id = TypeConverter.ObjectToInt(cmd.ExecuteScalar());
                    id = (int)cmd.LastInsertedId;//int.Parse(cmd.ExecuteScalar().ToString());

                    if (mustCloseConnection)
                    {
                        connection.Close();
                    }
                    return retval;
                }
            }
            catch (Exception ex)
            {

                throw;
            }
          
        }
        #endregion ExecuteNonQuery方法结束


        #region ExecuteDataset方法
        /// <summary>
        /// 执行指定数据库连接字符串的命令,返回DataSet.
        /// </summary>
        /// <param name="connStr">数据库连接字符串</param>
        /// <param name="commandText">SQL语句</param>
        /// <returns>返回一个包含结果集的DataSet</returns>
        public static DataSet ExecuteDataset(string commandText)
        {
            return ExecuteDataset(CommandType.Text, commandText);
        }

        /// <summary>
        /// 执行指定数据库连接字符串的命令,返回DataSet.
        /// </summary>
        /// <param name="connStr">数据库连接字符串</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
        /// <param name="commandText">SQL语句</param>
        /// <returns>返回一个包含结果集的DataSet</returns>
        public static DataSet ExecuteDataset(CommandType commandType, string commandText)
        {
            return ExecuteDataset(commandType, commandText, (MySqlParameter[])null);
        }

        /// <summary>
        /// 执行指定数据库连接字符串的命令,返回DataSet.
        /// </summary>
        /// <param name="connStr">数据库连接字符串</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
        /// <param name="commandText">SQL语句</param>
        /// <param name="commandParameters">SqlParameter参数数组</param>
        /// <returns>返回一个包含结果集的DataSet</returns>
        public static DataSet ExecuteDataset(CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            try
            {
                if (connStr == null || connStr.Length == 0) throw new ArgumentNullException("ConnectionString");

                // 创建并打开数据库连接对象,操作完成释放对象.

                using (MySqlConnection connection = new MySqlConnection())
                {
                    connection.ConnectionString = connStr;
                    connection.Open();

                    // 预处理
                    MySqlCommand cmd = new MySqlCommand();

                    bool mustCloseConnection = false;
                    PrepareCommand(cmd, connection, (MySqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);

                    using (MySqlDataAdapter da = new MySqlDataAdapter())
                    {
                        da.SelectCommand = cmd;
                        DataSet ds = new DataSet();

                        // 填充DataSet.
                        da.Fill(ds);

                        cmd.Parameters.Clear();

                        if (mustCloseConnection)
                            connection.Close();

                        return ds;
                    }
                }
            }
            catch (Exception ex)
            {
                //LogHelper.WriteError(typeof(DbHelper), "ExecuteDataset" + ex.Message);
                return null;
            }
        }
        #endregion ExecuteDataset数据集命令结束


        #region ExecuteScalar 返回结果集中的第一行第一列

        /// <summary>
        /// 执行指定数据库连接字符串的命令,返回结果集中的第一行第一列.
        /// </summary>
        /// <remarks>
        /// 示例:  
        ///  int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount");
        /// </remarks>
        /// <param name="connStr">数据库连接字符串</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
        /// <param name="commandText">存储过程名称或SQL语句</param>
        /// <returns>返回结果集中的第一行第一列</returns>
        public static object ExecuteScalar(CommandType commandType, string commandText)
        {
            // 执行参数为空的方法
            return ExecuteScalar(commandType, commandText, (MySqlParameter[])null);
        }

        /// <summary>
        /// 执行指定数据库连接字符串的命令,指定参数,返回结果集中的第一行第一列.
        /// </summary>
        /// <remarks>
        /// 示例:  
        ///  int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connStr">数据库连接字符串</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
        /// <param name="commandText">存储过程名称或SQL语句</param>
        /// <param name="commandParameters">分配给命令的SqlParamter参数数组</param>
        /// <returns>返回结果集中的第一行第一列</returns>
        public static object ExecuteScalar(CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            if (connStr == null || connStr.Length == 0) throw new ArgumentNullException("ConnectionString");
            // 创建并打开数据库连接对象,操作完成释放对象.
            using (MySqlConnection connection = new MySqlConnection())
            {
                connection.ConnectionString = connStr;
                // connection.Open();

                // 创建SqlCommand命令,并进行预处理
                MySqlCommand cmd = new MySqlCommand();

                bool mustCloseConnection = false;
                PrepareCommand(cmd, connection, (MySqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);

                // 执行SqlCommand命令,并返回结果.
                object retval = cmd.ExecuteScalar();

                // 清除参数,以便再次使用.
                cmd.Parameters.Clear();

                if (mustCloseConnection)
                    connection.Close();

                return retval;
            }
        }
        #endregion


        #region 执行ExecuteScalar,将结果以字符串类型输出。
        /// <summary>
        /// 执行ExecuteScalar,将结果以字符串类型输出。
        /// </summary>
        /// <param name="connStr">数据库连接字符串</param>
        /// <param name="commandType"></param>
        /// <param name="commandText"></param>
        /// <returns></returns>
        public static string ExecuteScalarToStr(CommandType commandType, string commandText)
        {
            object ec = ExecuteScalar(commandType, commandText);
            if (ec == null)
            {
                return "";
            }
            return ec.ToString();
        }

        /// <summary>
        /// 执行ExecuteScalar,将结果以字符串类型输出。
        /// </summary>
        /// <param name="connStr">数据库连接字符串</param>
        /// <param name="commandType"></param>
        /// <param name="commandText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static string ExecuteScalarToStr(CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            object ec = ExecuteScalar(commandType, commandText, commandParameters);
            if (ec == null)
            {
                return "";
            }
            return ec.ToString();
        }
        #endregion


        #region 执行ExecuteScalar,将结果以数字类型输出。
        /// <summary>
        /// 执行ExecuteScalar,将结果以数字类型输出。
        /// </summary>
        /// <param name="connStr">数据库连接字符串</param>
        /// <param name="commandType"></param>
        /// <param name="commandText"></param>
        /// <returns></returns>
        public static int ExecuteScalarToInt(CommandType commandType, string commandText)
        {
            object ec = ExecuteScalar(commandType, commandText);
            if (ec == null)
            {
                return -1;
            }
            return Convert.ToInt32(ec.ToString());
        }

        /// <summary>
        /// 执行ExecuteScalar,将结果以数字类型输出。
        /// </summary>
        /// <param name="connStr">数据库连接字符串</param>
        /// <param name="commandType"></param>
        /// <param name="commandText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static int ExecuteScalarToInt(CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            object ec = ExecuteScalar(commandType, commandText, commandParameters);
            if (ec == null)
            {
                return -1;
            }
            return Convert.ToInt32(ec.ToString());
        }
        #endregion


        #region 私有方法

        /// <summary>
        /// 将SqlParameter参数数组(参数值)分配给SqlCommand命令.
        /// 这个方法将给任何一个参数分配DBNull.Value;
        /// 该操作将阻止默认值的使用.
        /// </summary>
        /// <param name="command">命令名</param>
        /// <param name="commandParameters">SqlParameters数组</param>
        private static void AttachParameters(MySqlCommand command, MySqlParameter[] commandParameters)
        {
            if (command == null) throw new ArgumentNullException("command");
            if (commandParameters != null)
            {
                foreach (MySqlParameter p in commandParameters)
                {
                    if (p != null)
                    {
                        // 检查未分配值的输出参数,将其分配以DBNull.Value.
                        if ((p.Direction == ParameterDirection.InputOutput || p.Direction == ParameterDirection.Input) &&
                            (p.Value == null))
                        {
                            p.Value = DBNull.Value;
                        }
                        command.Parameters.Add(p);
                    }
                }
            }
        }

        /// <summary>
        /// 预处理用户提供的命令,数据库连接/事务/命令类型/参数
        /// </summary>
        /// <param name="command">要处理的SqlCommand</param>
        /// <param name="connection">数据库连接</param>
        /// <param name="transaction">一个有效的事务或者是null值</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本, 其它.)</param>
        /// <param name="commandText">存储过程名或都SQL命令文本</param>
        /// <param name="commandParameters">和命令相关联的SqlParameter参数数组,如果没有参数为'null'</param>
        /// <param name="mustCloseConnection"><c>true</c> 如果连接是打开的,则为true,其它情况下为false.</param>
        private static void PrepareCommand(MySqlCommand command, MySqlConnection connection, MySqlTransaction transaction, CommandType commandType, string commandText, MySqlParameter[] commandParameters, out bool mustCloseConnection)
        {
            if (command == null) throw new ArgumentNullException("command");
            if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText");

            // If the provided connection is not open, we will open it
            if (connection.State != ConnectionState.Open)
            {
                mustCloseConnection = true;
                connection.Open();
            }
            else
            {
                mustCloseConnection = false;
            }

            // 给命令分配一个数据库连接.
            command.Connection = connection;
            // 设置命令文本(存储过程名或SQL语句)
            command.CommandText = commandText;

            // 分配事务
            if (transaction != null)
            {
                if (transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
                command.Transaction = transaction;
            }

            // 设置命令类型.
            command.CommandType = commandType;

            // 分配命令参数
            if (commandParameters != null)
                AttachParameters(command, commandParameters);

            return;
        }

        #endregion 私有方法结束
    }

    public class NotifyPropertyChanged : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged 接口实现
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string propName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }
        #endregion
    }
}
